import { commonApi } from '../../../api/common'
import { $event } from '../../../utils'

// import { commonApi } from '/api/common'
Page({
  data: {
    hotCity: ['全国'],
    city: '暂无定位',
    cityList: [] as any[],
    showList: false,
  },
  async onLoad() {
    let hotCity = await commonApi.getHotCity()
    if (hotCity.length > 0) {
      hotCity = hotCity.map((item: any) => (item = item.split(' ')[item.split(' ').length - 1]))
      this.setData({
        hotCity: [...this.data.hotCity, ...hotCity],
      })
    }
    this.getCity()
  },
  /** 输入城市获取焦点 */
  showList() {
    this.setData({
      showList: true,
    })
  },
  /** 选择热门城市 */
  chooseCity(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e
    wx.setStorageSync('activityCity', item)
    wx.navigateBack({ delta: 1 })
    $event.emit('after:changeCity')
  },
  /** 获取地址 */
  getCity() {
    const city = wx.getStorageSync('activityCity')
    this.setData({
      city,
    })
  },
  /** 输入城市联想搜索 */
  inputCity(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    commonApi.getCity({ name: value }).then((res) => {
      this.setData({
        cityList: res,
      })
    })
  },
  /** 选择搜索出来的城市 */
  clickCity(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { city },
      },
    } = e
    wx.setStorageSync('activityCity', city)
    wx.navigateBack({ delta: 1 })
    $event.emit('after:changeCity')
  },

  /** 打开地图 */
  openLocation() {
    wx.chooseLocation({
      success: function (res) {
        const address = res.address as any
        const proExp = '.+[省]',
          cityExp = '.+[市]'
        const province: any = address.match(new RegExp(proExp)) // 省
        const match = address.match(new RegExp(cityExp))
        const city = match && match.length ? match[0].replace(province, '') : '' // 市

        wx.setStorageSync('activityCity', city || province || address)
        wx.navigateBack({ delta: 1 })
        $event.emit('after:changeCity')
      },
    })
  },
})
